package com.business.etl.flow.process;

import cn.hutool.core.collection.CollUtil;
import com.component.api.constants.FlowConstants;
import com.common.utils.constant.Constants;
import com.framework.redis.service.RedisService;
import org.apache.flink.types.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 描述：
 * 中间结果缓存
 * @author xianggj
 * @Date 2021/12/8 14:31
 **/
@Service
public class ResultCacheByRedis {


    @Autowired
    private RedisService redisService;

    /**
     * 控制map
     * 避免重复操作
     */
    @Deprecated
    private static final Map<String, Integer> COLLERTOR_MAP = new ConcurrentHashMap<>();

    /**
     * 缓存头
     * @param headers
     */
    public void setHeader(String nodeId, List<String> headers){
        redisService.del(FlowConstants.KEY_ + nodeId);
        String cols = CollUtil.join(headers, Constants.COMMA);
        redisService.lSet(FlowConstants.KEY_ + nodeId, cols);
//        COLLERTOR_MAP.put(nodeId, FlowConstants.MAX_LINE);
    }

    /**
     * 添加一行
     * @param objs
     */
    public void addLine(String nodeId, List<Object> objs){
        String data = CollUtil.join(objs, Constants.COMMA);
        addLineByStr(nodeId, data);
    }

    /**
     * 添加一行
     * @param rows
     */
    public void addRows(String nodeId,  List<String> rows){
        int max = Math.min(FlowConstants.MAX_LINE, rows.size());
        for (int i = 0; i < max; i++) {
            String row = rows.get(i);
            if (row == null){
                continue;
            }
            redisService.lSet(FlowConstants.KEY_ + nodeId, row);
        }
    }

    /**
     * 添加一行
     * @param rows
     */
    public void addStrs(String nodeId,  List<String> rows){
        if (rows == null){
            return;
        }
        for (int i = 0; i < rows.size(); i++) {
            String row = rows.get(i);
            if (row == null){
                continue;
            }
            redisService.lSet(FlowConstants.KEY_ + nodeId, row);
        }
    }

    /**
     * 添加一行
     * @param data
     */
    public boolean addLineByStr(String nodeId, String data){
        if (COLLERTOR_MAP.containsKey(nodeId)){
            Integer integer = COLLERTOR_MAP.get(nodeId);
            if (integer <= 0 ){
                COLLERTOR_MAP.remove(nodeId);
                return false;
            }
            redisService.lSet(FlowConstants.KEY_ + nodeId, data);
            COLLERTOR_MAP.put(nodeId, integer--);
            return true;
        }
        return false;
    }

}
